'use client';

import { useQuery } from '@tanstack/react-query';
import { queryMenus, queryMenuStatistics } from '@/services/api';
import type { IMenu, IMenuStatistics } from '@/interfaces';
import Box from '@/app/[locale]/admin/common/box';
import Alert from '@/app/[locale]/alert/alert';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { useRouter } from 'next/navigation';
import { type ChangeEvent, useState } from 'react';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function MenuAdminPage(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: IMenu[];
    translatedFields: PrefixedTTranslatedFields<'menuAdminPage'>;
  },
) {
  const [searchName, setSearchName] = useState('');
  const router = useRouter();

  const queryMenuStatisticsQuery = useQuery(
    ['/menus', '/statistics'],
    async () => {
      return (await queryMenuStatistics()) as IMenuStatistics;
    },
  );

  const queryMenusQuery = useQuery(
    ['/menus', searchName],
    async (context) => {
      return searchCore((await queryMenus()) as IMenu[], context.queryKey[1]);
    },
    {
      keepPreviousData: true,
      initialData: source,
    },
  );

  function onClickDetail(item: IMenu) {
    router.push(`menu/detail?id=${item.id}`);
  }

  function onClickAddSubmenus(item: IMenu) {
    router.push(`menu/submenu/create?id=${item.id}`);
  }

  function onClickUpdate(item: IMenu) {
    router.push(`menu/update?id=${item.id}`);
  }

  function onClickDelete(item: IMenu) {
    router.push(`menu/delete?id=${item.id}`);
  }

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value;
    setSearchName(value.toLowerCase());
  }

  function searchCore(data: IMenu[], searchName: string) {
    return searchName
      ? data.filter((item) => {
          return (
            item.name.includes(searchName) ||
            item.path.includes(searchName) ||
            (searchName === '链接' && item.menuType === 'LINK') ||
            (searchName === '按钮' && item.menuType === 'BUTTON')
          );
        })
      : data;
  }

  return (
    <div className="row g-4">
      <div className="col-12">
        <Box>
          <div className="row">
            <div className="col">
              <div className="card">
                <div className="card-body">
                  <h6 className="card-subtitle mb-2 text-secondary">
                    {translatedFields.count.menu}
                  </h6>
                  <h5 className="card-title">
                    {queryMenuStatisticsQuery.data &&
                      queryMenuStatisticsQuery.data.count}

                    {queryMenuStatisticsQuery.isError && (
                      <Alert
                        message={queryMenuStatisticsQuery.error}
                        type="error"
                      />
                    )}

                    {queryMenuStatisticsQuery.isLoading && <Spinner />}
                  </h5>
                </div>
              </div>
            </div>
            <div className="col">
              <div className="card">
                <div className="card-body">
                  <h6 className="card-subtitle mb-2 text-secondary">
                    {translatedFields.count.mainMenu}
                  </h6>
                  {queryMenuStatisticsQuery.data && (
                    <h5 className="card-title">
                      {queryMenuStatisticsQuery.data.count -
                        queryMenuStatisticsQuery.data.submenuCount}
                    </h5>
                  )}

                  {queryMenuStatisticsQuery.isError && (
                    <Alert
                      message={queryMenuStatisticsQuery.error}
                      type="error"
                    />
                  )}

                  {queryMenuStatisticsQuery.isLoading && <Spinner />}
                </div>
              </div>
            </div>
            <div className="col">
              <div className="card">
                <div className="card-body">
                  <h6 className="card-subtitle mb-2 text-secondary">
                    {translatedFields.count.submenu}
                  </h6>
                  <h5 className="card-title">
                    {queryMenuStatisticsQuery.data &&
                      queryMenuStatisticsQuery.data.submenuCount}

                    {queryMenuStatisticsQuery.isError && (
                      <Alert
                        message={queryMenuStatisticsQuery.error}
                        type="error"
                      />
                    )}

                    {queryMenuStatisticsQuery.isLoading && <Spinner />}
                  </h5>
                </div>
              </div>
            </div>
          </div>
        </Box>
      </div>
      <div className="col">
        <Box>
          <div className="card">
            <div className="card-header bg-transparent">
              <div className="row row-cols-auto justify-content-between g-2">
                <div className="col">
                  <div className="input-group">
                    <span className="input-group-text">
                      <i className="bi bi-search"></i>
                    </span>
                    <input
                      onChange={onChangeSearch}
                      type="search"
                      className="form-control"
                      placeholder={translatedFields.tip.searchPlaceholder}
                    />
                  </div>
                </div>
                <div className="col"></div>
              </div>
            </div>
            <div className="card-body vstack gap-4">
              <div className="table-responsive">
                <table className="table table-hover align-middle">
                  <thead>
                    <tr className="text-nowrap">
                      <th scope="col" className="">
                        ID
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.name}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.path}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.sort}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.menuType}
                      </th>
                      <th scope="col" className=""></th>
                    </tr>
                  </thead>
                  <tbody>
                    {queryMenusQuery.data.map((item) => {
                      return (
                        <tr key={item.id} className="text-nowrap">
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.id}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.name}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.path}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.sort}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {translatedFields.enums.menuType[item.menuType]}
                          </td>
                          <td>
                            <div className="hstack gap-2">
                              <button
                                onClick={onClickAddSubmenus.bind(this, item)}
                                className="btn btn-sm btn-light"
                                type="button"
                              >
                                <i className="bi bi-plus-lg me-2"></i>
                                {translatedFields.operate.addSubmenus}
                              </button>

                              <button
                                onClick={onClickUpdate.bind(this, item)}
                                className="btn btn-sm btn-light"
                                type="button"
                              >
                                <i className="bi bi-pencil me-2"></i>
                                {translatedFields.operate.update}
                              </button>

                              <button
                                onClick={onClickDelete.bind(this, item)}
                                className="btn btn-sm btn-light text-danger"
                                type="button"
                              >
                                <i className="bi bi-trash me-2"></i>
                                {translatedFields.operate.delete}
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {queryMenusQuery.data.length === 0 && <Nodata />}
            </div>
          </div>
        </Box>
      </div>
    </div>
  );
}
